<?php
declare (strict_types = 1);

namespace app\service;

use app\model\AccountRecordCategoryRelModel;
use app\model\AccountRecordModel;

class AccountRecordService extends \think\Service
{
    /**
     * 获取账单列表
     *
     * @return mixed
     */
    public function getList($data)
    {
        //按月份查找
        $query = AccountRecordModel::alias("a")
            ->join("gao_account_record_category_rel b ", "a.record_id = b.record_id ", "left")
            ->join("gao_account_category c ", "b.cate_id = c.cate_id ", "left")
            ->field("a.record_id,a.record_name,a.record_price,a.pay_time,c.cate_name,c.account_type")
            ->where("a.user_id", $data['user_id'])
            ->where("a.acc_id", $data['acc_id'])
            ->where("a.is_delete", 1)
            ->where("b.is_delete", 1)
            ->where("c.is_delete", 1);
        if (!empty($data['account_type'])) {
            $query = $query->where("c.account_type", $data['account_type']);
        }
        if (!empty($data['account_types'])) {
            $query = $query->whereIn("c.account_type", $data['account_types']);
        }
        if (!empty($data['pay_time'])) {
            $query = $query->whereMonth("a.pay_time");
        }
        $query = $query->order("a.pay_time", "desc");

        if(!empty($data['page_no']) && !empty($data['page_size'])){
            $list = $query->paginate([
                'list_rows' => $data['page_size'],
                'page' => $data['page_no']
            ]);
        }else{
            $list = $query->select();
        }
        return $list;
    }
    /**
     * 获取账单列表
     *
     * @return mixed
     */
    public function create($data)
    {
        //添加账单，同时要添加分类以及关联表数据
        $record = AccountRecordModel::create($data);
        $recordRel = AccountRecordCategoryRelModel::create($record->toArray());
        return $recordRel;
    }


    /**
     * 修改账单
     * @param $data
     */
    public function update($data)
    {
        $res = AccountRecordModel::where('record_id', $data['record_id'])->update($data);
        return $res;
    }

    /**
     * 获取账单
     */
    public function getOne($data)
    {
        $query = AccountRecordModel::where('is_delete', 1);
        if (!empty($data['record_id'])) {
            $query = $query->where("record_id", $data['record_id']);
        }
        if (!empty($data['user_id'])) {
            $query = $query->where("user_id", $data['user_id']);
        }
        if (!empty($data['acc_id'])) {
            $query = $query->where("acc_id", $data['acc_id']);
        }
        $rel = $query->find();
        return $rel;
    }
    /**
     * 伪删除账单
     */
    public function delete($data)
    {
        $res = AccountRecordModel::where('record_id', $data['record_id'])->update(['is_delete'=>2]);
        return $res;
    }
}
